/*
 未来之窗库 - 扩展版本
 javascript query design by cyberwin
 扩展功能: each方法、AJAX支持、WLZC_serializeJson方法
*/

// 已有代码保持不变，以下是扩展部分

// 1. 添加each方法
cyberwin_query.prototype.each = function(callback) {
    if (typeof callback === 'function') {
        for (var i = 0; i < this.elements.length; i++) {
            // 执行回调函数，传入索引和当前元素，this指向当前元素
            callback.call(this.elements[i], i, this.elements[i]);
        }
    }
    return this; // 支持链式调用
};

// 2. AJAX相关功能
// 全局AJAX设置
var cyberwin_ajaxSettings = {
    type: 'GET',
    url: '',
    data: null,
    async: true,
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    error: function() {},
    success: function() {},
    complete: function() {}
};

// AJAX设置方法
$cq.ajaxSetup = function(options) {
    for (var key in options) {
        if (options.hasOwnProperty(key)) {
            cyberwin_ajaxSettings[key] = options[key];
        }
    }
};

// AJAX核心方法
$cq.ajax = function(options) {
    // 合并配置，优先级：调用时传入 > 全局设置
    var settings = {};
    for (var key in cyberwin_ajaxSettings) {
        settings[key] = cyberwin_ajaxSettings[key];
    }
    for (var key in options) {
        if (options.hasOwnProperty(key)) {
            settings[key] = options[key];
        }
    }

    // 创建XMLHttpRequest对象
    var xhr;
    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    } else {
        // 兼容IE6及以下
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }

    // 处理数据
    var dataStr = '';
    if (settings.data && typeof settings.data === 'object') {
        for (var key in settings.data) {
            if (settings.data.hasOwnProperty(key)) {
                dataStr += encodeURIComponent(key) + '=' + encodeURIComponent(settings.data[key]) + '&';
            }
        }
        dataStr = dataStr.slice(0, -1);
    }

    // 处理URL（GET方法时附加数据）
    var url = settings.url;
    if (settings.type.toUpperCase() === 'GET' && dataStr) {
        url += (url.indexOf('?') > -1 ? '&' : '?') + dataStr;
        dataStr = null; // GET方法不需要send数据
    }

    // 打开连接
    xhr.open(settings.type, url, settings.async);

    // 设置请求头
    for (var key in settings.headers) {
        if (settings.headers.hasOwnProperty(key)) {
            xhr.setRequestHeader(key, settings.headers[key]);
        }
    }

    // 处理响应
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            // 调用完成回调
            settings.complete(xhr);
            
            if (xhr.status >= 200 && xhr.status < 300) {
                // 成功回调
                var responseData;
                try {
                    // 尝试解析JSON
                    responseData = JSON.parse(xhr.responseText);
                } catch (e) {
                    // 解析失败则返回原始文本
                    responseData = xhr.responseText;
                }
                settings.success(responseData, xhr.status, xhr);
            } else {
                // 错误回调
                settings.error(xhr, xhr.status, xhr.statusText);
            }
        }
    };

    // 发送请求
    xhr.send(dataStr);
    
    // 返回xhr对象，方便中断请求等操作
    return xhr;
};

// 快捷GET方法
$cq.get = function(url, data, success, dataType) {
    // 处理参数重载
    if (typeof data === 'function') {
        dataType = success;
        success = data;
        data = null;
    }
    
    return $cq.ajax({
        type: 'GET',
        url: url,
        data: data,
        success: success
    });
};

// 快捷POST方法
$cq.post = function(url, data, success, dataType) {
    // 处理参数重载
    if (typeof data === 'function') {
        dataType = success;
        success = data;
        data = null;
    }
    
    return $cq.ajax({
        type: 'POST',
        url: url,
        data: data,
        success: success
    });
};

// 3. 添加WLZC_serializeJson方法
cyberwin_query.prototype.WLZC_serializeJson = function() {
    var wlzc_serializeObj = {};
    var elements = this.elements[0] ? this.elements[0].elements : [];
    
    // 收集表单数据
    var array = [];
    for (var i = 0; i < elements.length; i++) {
        var elem = elements[i];
        // 跳过禁用的元素和没有name属性的元素
        if (elem.disabled || !elem.name) continue;
        
        // 处理复选框和单选按钮
        if ((elem.type === 'checkbox' || elem.type === 'radio') && !elem.checked) continue;
        
        array.push({
            name: elem.name,
            value: elem.value
        });
    }
    
    // 处理数据结构
    for (var i = 0; i < array.length; i++) {
        var item = array[i];
        var wlzc_ei_name = item.name;
        var ie = wlzc_ei_name.indexOf("[");
        
        if (ie >= 0) {
            // 处理数组形式的name，如ymethod[1][paymethod_id]
            var wlzc_ei_name_yh1 = wlzc_ei_name.replace(/]/g, "");
            var wlzc_ei_name_Array = wlzc_ei_name_yh1.split("[");
            var wlzc_ei_len = wlzc_ei_name_Array.length;
            
            if (wlzc_ei_len === 3) {
                var array_1 = wlzc_ei_name_Array[0];
                var array_2 = wlzc_ei_name_Array[1];
                var array_3 = wlzc_ei_name_Array[2];
                
                // 初始化嵌套对象
                if (!wlzc_serializeObj[array_1]) {
                    wlzc_serializeObj[array_1] = {};
                }
                if (!wlzc_serializeObj[array_1][array_2]) {
                    wlzc_serializeObj[array_1][array_2] = {};
                }
                
                // 赋值
                wlzc_serializeObj[array_1][array_2][array_3] = item.value;
            }
        } else {
            // 处理普通name
            if (wlzc_serializeObj[wlzc_ei_name]) {
                if (Array.isArray(wlzc_serializeObj[wlzc_ei_name])) {
                    wlzc_serializeObj[wlzc_ei_name].push(item.value);
                } else {
                    wlzc_serializeObj[wlzc_ei_name] = [wlzc_serializeObj[wlzc_ei_name], item.value];
                }
            } else {
                wlzc_serializeObj[wlzc_ei_name] = item.value;
            }
        }
    }
    
    return wlzc_serializeObj;
};
